package util

import (
	"context"
	"fmt"
	"gg_server/db"
	"gg_server/model"
	"gg_server/response"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// mongodb的操作

type MongoDStruct struct{}

var MongoD *MongoDStruct

func init() {
	MongoD = &MongoDStruct{}
}

// 查找 聊天内容 文档
func (m *MongoDStruct) GetChat(filter primitive.D) (chat model.Chat) {

	// 查询聊天记录
	err := db.CreateMongoDB().Collection("chat").FindOne(context.TODO(), filter).Decode(&chat)
	if err != nil {
		response.GetError().ServerError(fmt.Sprint("查询聊天信息时出错,err:", err))
		return
	}

	return
}

// 更新聊天信息内容 状态为已读 并返回聊天信息
func (m *MongoDStruct) FindOnUpdateChatRead(_id primitive.ObjectID, friend_id int, chat *model.Chat) {
	identifier := []interface{}{
		bson.D{{
			Key: "elem.id",
			Value: bson.D{{
				Key:   "$eq",
				Value: friend_id,
			}},
		}},
	}

	update := bson.D{
		{
			Key: "$set",
			Value: bson.D{
				{
					Key:   "chat.$[elem].read",
					Value: true,
				},
			},
		},
	}

	opts := options.FindOneAndUpdate().SetArrayFilters(options.ArrayFilters{Filters: identifier}).SetReturnDocument(options.After)

	err := db.CreateMongoDB().Collection("chat").FindOneAndUpdate(context.TODO(), bson.D{{Key: "_id", Value: _id}}, update, opts).Decode(&chat)
	if err != nil {
		response.GetError().ServerError(fmt.Sprint("查找聊天内容时出现了错误,err:", err))
	}
}

// 添加 聊天消息
func (m *MongoDStruct) PushChatMsg(_id primitive.ObjectID, chat model.ChatMsg) {

	filter := bson.D{{
		Key:   "_id",
		Value: _id,
	}}

	update := bson.D{{
		Key: "$push",
		Value: bson.D{{
			Key:   "chat",
			Value: chat,
		}},
	}}

	db.CreateMongoDB().Collection("chat").UpdateOne(context.TODO(), filter, update)
}
